/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package hybris;

import java.awt.Color;
import java.awt.Graphics;

/**
 *
 * @author menderleit
 */
public class Quad3D {
    private Vector3[] vec;
    private Vector3[] tVec;
    private Color col;
    
    public Quad3D() {
        vec = new Vector3[4];
        tVec = new Vector3[4];
        for(int i=0; i<4; i++) {
            vec[i] = new Vector3();
        }
        col = new Color(255,255,255);
    }
    
    public void setColor(Color col) {
        this.col = col;
    }
    
    public void setVector(int v, Vector3 v3) {
        if(v >= 0 && v <= 3) {
            vec[v].set(v3.getX(), v3.getY(), v3.getZ());
        }
    }
    
    public Vector3 getNormal() {
        Vector3 e1, e3, n;
        e1 = tVec[1].subtract(tVec[0]);
        e3 = tVec[3].subtract(tVec[0]);
        n = e1.crossProduct(e3);
        n = n.normalize();
        return n;
    }
    
    public Vector3 getVector(int v) {
        Vector3 rV = null;
        if(v >= 0 && v <= 3) {
            rV = vec[v];
        }
        return rV;
    }
    
    public void draw(Graphics g, int screenWidth, int screenHeight, double POV, Vector3 pos, Vector3 rot) {
        int[] xP = new int[4];
        int[] yP = new int[4];
        for(int i=0; i<4; i++) {
            tVec[i] = vec[i].copy();
            tVec[i].rotate(rot);
            tVec[i].move(pos);
            tVec[i].project(POV);
            tVec[i].map(screenWidth, screenHeight);
            xP[i] = tVec[i].getSX();
            yP[i] = tVec[i].getSY();
        }
        double d = getNormal().dotProduct(new Vector3(0,0,0).subtract(tVec[0]));
        if(d > 0) {
            d = getNormal().dotProduct(new Vector3(25,25,0).subtract(tVec[0]));
            double red = col.getRed() * ((d+22.5)/45.0);
            double green = col.getGreen() * ((d+22.5)/45.0);
            double blue = col.getBlue() * ((d+22.5)/45.0);
            g.setColor(new Color(wrapColor((int)red), wrapColor((int)green), wrapColor((int)blue), col.getAlpha()));
            g.fillPolygon(xP, yP, 4);
        }
    }
    
    public int wrapColor(int col) {
        int newCol = col;
        if(col < 0) {
            newCol = 0;
        }
        if(col > 255) {
            newCol = 255;
        }
        return newCol;
    }
}
